package com.zhiyou100.test.test02.xml;

import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;

/**
 * @author yang
 * @className Demo01DomRead
 * @packageName com.zhiyou100.test.test02.xml
 * @Description TODO demo 解析练习1
 * @date 2020-08-07 14:27
 */
public class Demo01DomRead {
    /**
     * @return org.w3c.dom.Document
     * @Description TODO 读取 xml 为 document 对象
     * @name xml2Doc
     * @param: [path]
     * @date 8/7/20 14:31
     * @author yang
     */
    public static Document xml2Doc(String path) throws Exception {
        // 获取文档解析器工厂对象
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        // 通过工厂对象获取解析器对象
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        // 通过解析器的 parse 方法，把 xml 解析为 document 对象
        return documentBuilder.parse(new File(path));
    }


    public static void read() throws Exception {
        Document document = xml2Doc("src/main/java/com/zhiyou100/test02/xml/Test01.xml");

        NodeList student = document.getElementsByTagName("student");

        for (int i = 0; i < student.getLength(); i++) {
            Node node = student.item(i);
            Element eleStu = (Element) node;
            NamedNodeMap attributes = eleStu.getAttributes();
            for (int j = 0; j < attributes.getLength(); j++) {
                Attr attr = (Attr) attributes.item(j);
                System.out.println(attr);
                System.out.println(attr.getName() + " === " + attr.getValue());
            }
            System.out.println("----------------");
            Element parentNode = (Element) eleStu.getParentNode();
            System.out.println(parentNode.getNodeName() + " ==== " + parentNode.getNodeType());

            NodeList childNodes = parentNode.getChildNodes();

            for (int j = 0; j < childNodes.getLength(); j++) {
                if (childNodes.item(j).getNodeType() == 1) {
                    Element item = (Element) childNodes.item(j);
                    System.out.println("子标签  " + item.getNodeName() + " 的文本内容是 " + item.getTextContent());
                }
            }
        }


    }


    public static void main(String[] args) throws Exception {
        read();
    }

}
